/**
 * anji-allways.com Inc.
 * Copyright (c) 2016-2017 All Rights Reserved.
 */
package cn.zhiwen.service.impl;

import cn.zhiwen.entity.CrmAuth;
import cn.zhiwen.entity.Customer;
import cn.zhiwen.entity.CustomerRequest;
import cn.zhiwen.entity.CustomerResult;
import cn.zhiwen.entity.DealerIdAndCode;
import cn.zhiwen.entity.DealerOfBrand;
import cn.zhiwen.entity.DimIdAndCode;
import cn.zhiwen.entity.UserEntity;
import cn.zhiwen.entity.UserRoleEntity;
import cn.zhiwen.mapper.CrmAuthMapper;
import cn.zhiwen.mapper.CustomerMapper;
import cn.zhiwen.mapper.UserMapper;
import cn.zhiwen.mapper.UserRoleMapper;
import cn.zhiwen.service.CustomerService;
import cn.zhiwen.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

/**
 * <pre>
 * 客户管理服务
 * </pre>
 *
 * @author wangzhenming
 * @version $Id: CustomerServiceImpl.java, v 0.1 2018年2月27日 下午2:12:19 clps Exp $
 */
@Service("customerService")
public class CustomerServiceImpl implements CustomerService {

    Logger logger = Logger.getLogger("cn.zhiwen.service.impl.CustomerServiceImpl");

    @Autowired
    private CrmAuthMapper crmAuthMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Transactional
    public Integer insertIntoCustomerRequest(CustomerRequest reqData) {
        try {
            //验证手机号是否重复
            int count = customerMapper.queryInkelIsCF(reqData.getLinktel());
            if(count != 0){
                return 000010;
            }

            // TODO Auto-generated method stub
            List<DealerOfBrand> dealerOfBrands = reqData.getDealerOfBrands();
            ArrayList<DimIdAndCode> dimIdAndCodes = new ArrayList<DimIdAndCode>();
            CustomerResult customerResult = new CustomerResult();
            logger.info("===================插入customer表");
            if (!"1".equals(reqData.getCusttype())) {
                for (DealerOfBrand dealerOfBrand : dealerOfBrands) {
                    if (dealerOfBrand.getBrandCode() != null && !dealerOfBrand.getBrandCode().isEmpty()) {
                        // 角色为主机厂或者经销商时，循环遍历主机厂，解析brandCode
                        DimIdAndCode dimIdAndCode = getBrandCodeAndId(dealerOfBrand.getBrandCode());
                        if ("3".equals(reqData.getCusttype())) {
                            // 解析dealerCodes
                            List<DealerIdAndCode> dealerIdAndCodes = getDealerIdAndCodes(dealerOfBrand);
                            Integer type = getType(dimIdAndCode.getCode());
                            dimIdAndCode.setList(dealerIdAndCodes);
                            dimIdAndCode.setType(type);
                        }
                        dimIdAndCodes.add(dimIdAndCode);
                    }
                }
                customerResult.setDimId(dimIdAndCodes.get(0).getId());
                customerResult.setBrandCode(dimIdAndCodes.get(0).getCode());
                if ("3".equals(reqData.getCusttype())) {
                    logger.info("此时客户类别为经销商");
                    customerResult.setDealerid(dimIdAndCodes.get(0).getList().get(0).getDealerId());
                    customerResult.setDealerCode(dimIdAndCodes.get(0).getList().get(0).getDealerCode());
                    customerResult.setType(dimIdAndCodes.get(0).getType());
                }
            }

            customerResult.setLinktel(reqData.getLinktel());
            customerResult.setCanReceive(reqData.getCanReceive());
            customerResult.setCustname(reqData.getCustname());
            customerResult.setCusttype(reqData.getCusttype());
            logger.info("设置初始密码123456");
            String encryptBySalt = MD5Util.getInstance().encryptBySalt("123456");
            Integer customerId = insertIntoCustomer(customerResult, encryptBySalt);
            if ("3".equals(reqData.getCusttype())) {
                // 移除默认的经销商
                dimIdAndCodes.get(0).getList().remove(0);
                if (dimIdAndCodes.size() > 1 || dimIdAndCodes.get(0).getList().size() != 0) {
                    // 非单个经销商的操作
                    logger.info("======================插入auth表");
                    insertCustomerBylist(dimIdAndCodes, customerId, reqData.getCusttype());
                }
            }
            if ("2".equals(reqData.getCusttype())) {
                // 移除默认的主机厂
                dimIdAndCodes.remove(0);
                if (dimIdAndCodes.size() != 0) {
                    // 非单个主机厂的操作
                    logger.info("======================插入auth表");
                    insertCustomerBylist(dimIdAndCodes, customerId, reqData.getCusttype());
                }
            }
            return customerId;
        } catch (Exception e) {
            logger.info("新增customer出现异常");
            return null;
        }
    }

    private DimIdAndCode getBrandCodeAndId(String brandCode) {
        // TODO Auto-generated method stub
        logger.info("=====所属主体加ID=========" + brandCode);
        DimIdAndCode dimIdAndCode = new DimIdAndCode();
        String[] split = brandCode.split("-");
        int id = Integer.parseInt(split[0]);
        dimIdAndCode.setId(id);
        dimIdAndCode.setCode(split[1]);
        return dimIdAndCode;
    }

    private List<DealerIdAndCode> getDealerIdAndCodes(DealerOfBrand dealerOfBrand) {
        // TODO Auto-generated method stub
        List<String> dealerIdCodes = dealerOfBrand.getDealerIdCodes();
        List<DealerIdAndCode> list = new ArrayList<DealerIdAndCode>();
        for (String dealerIdCode : dealerIdCodes) {
            String[] idAndCode = dealerIdCode.split("-");
            Integer dealerId = (Integer) Integer.parseInt(idAndCode[0]);
            DealerIdAndCode dealerIdAndCode = new DealerIdAndCode();
            dealerIdAndCode.setDealerCode(idAndCode[1]);
            dealerIdAndCode.setDealerId(dealerId);
            logger.info("经销商dealerIdAndCode:" + dealerIdAndCode.toString());
            list.add(dealerIdAndCode);

        }
        return list;
    }

    private Integer getType(String brandCode) {
        // TODO Auto-generated method stub
        if ("LSV".equalsIgnoreCase(brandCode)) {
            // 经销商来源为经销商表
            return 1;
        } else {
            // 经销商来源为仓库表
            return 2;
        }

    }

    public Integer insertIntoCustomer(CustomerResult reqData, String encryptBySalt) {
        try {
            Customer customer = new Customer();
            customer.setCustname(reqData.getCustname());
            customer.setLinktel(reqData.getLinktel());
            customer.setCreateTime(new Date());
            customer.setUpdateTime(new Date());
            customer.setDealerid(reqData.getDealerid());
            customer.setBrandcode(reqData.getBrandCode());
            customer.setPassword(encryptBySalt);
            customer.setCusttype(reqData.getCusttype());
            customer.setDimId(reqData.getDimId());
            customer.setDimCode(reqData.getBrandCode());
            customer.setType(reqData.getType());
            customer.setDealerCode(reqData.getDealerCode());
            customer.setCanReceive(reqData.getCanReceive());
            customer.setAuthflag(0);
            customerMapper.insert(customer);
            return customer.getId();

        } catch (Exception e) {
            logger.info("新增用户异常");
            return null;
        }

    }

    private void insertCustomerBylist(ArrayList<DimIdAndCode> dimIdAndCodes, Integer customerId, String custtype) {
        // TODO Auto-generated method stub
        List<CrmAuth> list = new ArrayList<CrmAuth>();
        logger.info("=======插入crmauth表，角色为经销商");
        for (DimIdAndCode dimIdAndCode : dimIdAndCodes) {
            if ("3".equals(custtype)) {
                List<DealerIdAndCode> dealerIdAndCodes = dimIdAndCode.getList();
                for (DealerIdAndCode dealerIdAndCode : dealerIdAndCodes) {
                    CrmAuth crmAuth = new CrmAuth();
                    crmAuth.setCustomerId(customerId);
                    crmAuth.setCrmDelarId(dealerIdAndCode.getDealerId());
                    crmAuth.setCrmDelarCode(dealerIdAndCode.getDealerCode());
                    crmAuth.setType(dimIdAndCode.getType());
                    crmAuth.setDimCode(dimIdAndCode.getCode());
                    crmAuth.setDimId(dimIdAndCode.getId());
                    crmAuth.setIsAccept(0);
                    list.add(crmAuth);
                }
            } else {
                logger.info("=======插入crmauth表，角色为主机厂");
                CrmAuth crmAuth = new CrmAuth();
                crmAuth.setCustomerId(customerId);
                crmAuth.setDimCode(dimIdAndCode.getCode());
                crmAuth.setDimId(dimIdAndCode.getId());
                crmAuth.setIsAccept(0);
                list.add(crmAuth);
            }
        }
        logger.info("==============更新CRMAuth表");
        crmAuthMapper.insertByList(list);

    }

    @Transactional
    public Integer insertUserAndRole(CustomerRequest reqData) {
        //经销商
        if(reqData.getCusttype().equals("3")){
            UserEntity userEntity = new UserEntity();
            userEntity.setIsCheck(0);
            userEntity.setUserName(reqData.getCustname());
            userEntity.setIsDel(0);
            String encryptBySalt = MD5Util.getInstance().encryptBySalt("123456");
            userEntity.setPassword(encryptBySalt);
            userEntity.setStatus(0);
            userEntity.setOrgId(3);
            userEntity.setOrgType(3);
            userEntity.setCreateTime(new Date());
            userEntity.setUpdateTime(new Date());
            userEntity.setTelephone(reqData.getLinktel());
            userEntity.setId((long) reqData.getId());
            userMapper.insertUser(userEntity);

            UserRoleEntity userRoleEntity = new UserRoleEntity();
            userRoleEntity.setUserId((long)reqData.getId());
            userRoleEntity.setRoleId(37L);
            userRoleEntity.setCreateTime(new Date());
            userRoleMapper.insertRole(userRoleEntity);
        }
        return 1;
    }
}
